using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Xml;
using Microsoft.Win32;
using System.Xml.XPath;

namespace CaptureLinks
{
    public partial class MainForm : Form
    {
        #region Public_Private Field
        string strSiteURL = "";
        SPLinkLists.Lists listWS;
        string strLinkTitle = "";
        string strLinkURL = "";
        string strLinkDescription = "";
        bool check = false;
        #endregion

        #region CTOR
        public MainForm()
        {
            InitializeComponent();

        }
        #endregion

        #region Event Handlers
        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Application.StartupPath +"\\Link.xml");
            //Fill Selected Page Title 
            XmlNodeList Title = xmlDoc.GetElementsByTagName("Title");
            strLinkTitle = Title[0].InnerText;
            this.txtBox_Title.Text = strLinkTitle;
            //Fill Selected Page Url 
            XmlNodeList URL = xmlDoc.GetElementsByTagName("URL");
            strLinkURL = URL[0].InnerText;
            this.txtBoxSelectedLink.Text = strLinkURL;
            //Fill Selected Page Description 
            XmlNodeList Description = xmlDoc.GetElementsByTagName("Description");
            strLinkDescription = Description[0].InnerText;
            this.txtBox_Description.Text = strLinkDescription;

            //Fill SharePoint Site DropDown from settings.
            LoadSiteUrl();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string strUrl = "";
            strUrl = this.cmbSiteUrl.Text;
            if (strUrl != "")
            {
                
                strSiteURL = this.cmbSiteUrl.Text;
                 Fill_LinkListTree();
                //if(check == true)
                 btnAddLink.Enabled = true;
            }
            else
            {
                MessageBox.Show("SharePoint Site url can not be empty, Enter the Url and click Connect");
            }
        }

        private void btnAddLink_Click(object sender, EventArgs e)
        {
            
            check = AddNew_LinkListItem();
            if (check)
                MessageBox.Show("["+strLinkTitle + "]added successfully!!!");
            else
                MessageBox.Show("Error-[" + strLinkTitle + "]could not be added, please check the List Name");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Settings_Click(object sender, EventArgs e)
        {
            CaptureLinksSettings.frmOptions objfrmOptions = new CaptureLinksSettings.frmOptions(null);
            objfrmOptions.ShowDialog();
        }

        #endregion

        #region Supporting Functions

        private void LoadSiteUrl()
        {
            string fileName = Application.StartupPath + "\\Options.xml";
            XPathDocument doc = new XPathDocument(fileName);
            XPathNavigator nav = doc.CreateNavigator();

            // Compile a standard XPath expression
            XPathExpression expr;
            expr = nav.Compile("//@SiteUrl");
            XPathNodeIterator iterator = nav.Select(expr);
            try
            {
                while (iterator.MoveNext())
                {
                    XPathNavigator nav2 = iterator.Current.Clone();
                    cmbSiteUrl.Items.Add(nav2.Value);
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void Fill_LinkListTree()
        {
            try
            {
            listWS = new SPLinkLists.Lists(strSiteURL + "/_vti_bin/Lists.asmx");
            listWS.Credentials = System.Net.CredentialCache.DefaultCredentials;

            listWS.Url = strSiteURL + "/_vti_bin/Lists.asmx";

                System.Xml.XmlNode xmlNode = listWS.GetListCollection();



                TreeNode listNode = new TreeNode("Link Lists");
                foreach (System.Xml.XmlNode childNode in xmlNode)
                {
                    if (childNode.Attributes["Hidden"].Value == "False")
                    {
                        if (childNode.Attributes["BaseType"].Value == "0")
                        {
                            //Find all Link List in side the Site
                            if (childNode.Attributes["ServerTemplate"].Value == "103")
                                listNode.Nodes.Add(childNode.Attributes["Title"].Value).ImageIndex = 4;
                        }
                        listNode.Tag = "LinkList";
                    }
                }

                tv_LinkList.Nodes.Add(listNode);
            }
            catch (Exception ex)
            {
                MessageBox.Show("SharePoint Site url can not be empty, Enter the Url and click Connect");
                
            }

        }

        private bool AddNew_LinkListItem()
        {

            /*Declare and initialize a variable for the Lists Web service.*/
            listWS = new SPLinkLists.Lists(strSiteURL + "/_vti_bin/Lists.asmx");

            /*Authenticate the current user by passing their default
            credentials to the Web service from the system credential cache.*/
            listWS.Credentials = System.Net.CredentialCache.DefaultCredentials;

            /*Set the Url property of the service for the path to a subsite.*/
            listWS.Url = strSiteURL + "/_vti_bin/Lists.asmx";

            // Create an XmlDocument object and construct a Batch element and its attributes.
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.Xml.XmlElement batchElement = doc.CreateElement("Batch");

            String strTitle = txtBox_Title.Text.ToString();
            String strURL = txtBoxSelectedLink.Text.ToString();
            //Create the URL in Url and Title form. 
            strURL = strURL + ", " + strTitle;
            String strDescription = txtBox_Description.Text.ToString();

            batchElement.InnerXml
                = "<Method ID='1' Cmd='New'>"
                + "<Field Name='URL'>" + strURL + "</Field>"
                + "<Field Name='Comments'>" + strDescription + "</Field>"
                + "</Method>";
            try
            {
                // Update list items.
                XmlNode ndRet
                    = listWS.UpdateListItems(tv_LinkList.SelectedNode.Text, batchElement);
                check = true;
                return check;
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                //MessageBox.Show(ex.Detail.InnerText);
                check = false;
                return check;
            }

        }

        #endregion


    }
}